#!/usr/bin/env python
#-*- coding: utf-8 -*-

import MySQLdb
import datetime
import httplib 
import urllib2,urllib
import json
import time

DB_HOST='localhost'
DB_USER='root'
DB_PASSWD='root123'
DB_PORT=3306
DB_NAME='weixin'
DB_CHARSET="utf8"

def select_db(sql):
    try:
        conn=MySQLdb.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASSWD, port=DB_PORT, charset=DB_CHARSET)
        cur=conn.cursor()
         
        conn.select_db(DB_NAME)
     
        count=cur.execute(sql)
        
        results=cur.fetchall()
                    
        conn.commit()
        cur.close()
        conn.close()
     
    except MySQLdb.Error,e:
         print "Mysql Error %d: %s" % (e.args[0], e.args[1])
         exit(1)
         
    return results

def update_db(sql):
    try:
        conn=MySQLdb.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASSWD, port=DB_PORT, charset=DB_CHARSET)
        cur=conn.cursor()
         
        conn.select_db(DB_NAME)
     
        count=cur.execute(sql)

        conn.commit()
        cur.close()
        conn.close()
     
    except MySQLdb.Error,e:
         print "Mysql Error %d: %s" % (e.args[0], e.args[1])
         exit(1)
         
    return count

def get_cur_timestamp():
    str=datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
    return str[0:17]

def get_access_token():
    req = urllib2.Request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxeffd2be40c37a1e3&secret=69974455532118a160dab7896d668157")
    response = urllib2.urlopen(req)
    the_page = response.read()
    content = json.loads(the_page, strict=False)
    return content["access_token"]

def msg_reply(token, touser, key):
    found_flg = 0
    str = "select reply from key_reply_msg where input_key = '%s';" % key
    print str
    results=select_db(str)
    for result in results:
        tmp = result[0].replace("\r", "\\r")
        tmp = tmp.replace("\n", "\\n")
        str = "{'touser':'%s','msgtype':'text','text':{'content':'%s'}}" % (touser, tmp)
        found_flg = 1
        
    if found_flg == 0:
        reply = unicode("对不起，找不到您需要的信息", "utf-8")
        #import sys
        #reload(sys)
        #sys.setdefaultencoding("utf8")
        #reply = "无法显示"
        str = '{"touser":"%s","msgtype":"text","text":{"content":"%s"}}' % (touser, reply)
        
    values = eval(str)
    data = json.dumps(values, ensure_ascii=False)
    url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s" % token
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    the_page = response.read()
    content = json.loads(the_page, strict=False)
    print content
    if content['errcode']:
        print content['errmsg']
        return 1

    return 0
    
#main
while True:        
    results=select_db('select * from msg_from_user where proc_flag = 0 order by create_time')
    sleep_flg=1
    for result in results:
        sleep_flg=0
        
        id=result[0]
        to_user=result[1]
        from_user=result[2]
        msg_type=result[4]
        content=result[5]
        update_time=result[8]
        
        time_stamp=get_cur_timestamp()
        count = update_db('update msg_from_user set proc_flag = 1, update_time = \'%s\' where id = %s and update_time = \'%s\'' % (time_stamp, id, update_time))
        if count == 0:
            continue
            
        token=get_access_token()
        if token != "":
            ret = msg_reply(token, from_user, content)
            if ret == 0:
                last_update_time = time_stamp
                time_stamp=get_cur_timestamp()
                update_db('update msg_from_user set proc_flag = 2, update_time = \'%s\' where id = %s and update_time = \'%s\'' % (time_stamp, id, last_update_time))
            
    if sleep_flg:
        print "into sleep"
        time.sleep(1)
    

